package com.zzh.lib.bar.extension

import android.graphics.Color
import android.os.Build
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.annotation.RequiresApi
import androidx.fragment.app.FragmentActivity

internal fun FragmentActivity.setSystemUiFlagWithLight(
    statusBarLight: Boolean,
    navigationBarLight: Boolean
) {
    window?.decorView?.systemUiVisibility = systemUiFlag(statusBarLight, navigationBarLight)
}

internal fun FragmentActivity.setStatusBarSystemUiFlagWithLight(light: Boolean) {
    window?.decorView?.systemUiVisibility = statusBarSystemUiFlag(light)
}

internal fun FragmentActivity.barTransparent() {
    statusBarTransparent()
    navigationBarTransparent()
}

internal fun FragmentActivity.statusBarTransparent() {
    when {
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
            window.isStatusBarContrastEnforced = false
        }
    }
    window.statusBarColor = Color.TRANSPARENT
}

internal fun FragmentActivity.navigationBarTransparent() {
    when {
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
            window.isNavigationBarContrastEnforced = false
        }
    }
    window.navigationBarColor = Color.TRANSPARENT
}

private fun systemUiFlag(statusBarLight: Boolean, navigationBarLight: Boolean): Int {

    var flag = (View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
    when {
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
            if (statusBarLight) flag = flag or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            if (navigationBarLight) flag = flag or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
        }

        else -> {
            if (statusBarLight) flag = flag or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        }

    }
    return flag
}

private fun statusBarSystemUiFlag(light: Boolean): Int {

    var flag = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
    if (light) flag = flag or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
    return flag
}

internal val FragmentActivity.decorView: ViewGroup?
    get() = window?.decorView as ViewGroup?

internal val FragmentActivity.contentView: ViewGroup?
    get() = decorView?.findViewById(android.R.id.content)

internal val FragmentActivity.rootView: View?
    get() = contentView?.getChildAt(0)

internal val FragmentActivity.originStatusBarColor: Int
    get() = window?.statusBarColor ?: Color.TRANSPARENT

internal val FragmentActivity.originNavigationBarColor: Int
    get() = window?.navigationBarColor ?: Color.TRANSPARENT